package com.atguigu.szdz.dcsyl.Filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Component
public class MyLogFilter implements Filter {
    private final RedisTemplate<String, Object> redisTemplate;

    public MyLogFilter(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("MyLogFilter 初始化...");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        System.out.println("请求路径：" + httpRequest.getRequestURI());

        String excpath = "/sys/login,/sys/register,/pmjl/aaa,/ylyc/aaa";
        List<String> excpathList = Arrays.asList(excpath.split(","));

        if (httpRequest.getRequestURI().contains("swagger") || httpRequest.getRequestURI().contains("/v3/")) {
            chain.doFilter(request, response);
        } else if (excpathList.contains(httpRequest.getRequestURI())) {
            System.out.println("直接放行!");
            chain.doFilter(request, response);
        } else {
            String token = httpRequest.getHeader("token");
            String userId = httpRequest.getHeader("userId");
            if (token == null) {
                httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN); // 设置状态码为403
                httpResponse.setContentType("application/json"); // 设置内容类型为JSON
                httpResponse.setCharacterEncoding("UTF-8");
                httpResponse.getWriter().write("{\"error\":\"Access denied\"}"); // 返回错误信息
                return; // 终止过滤链的进一步处理
            }

            String value = (String) redisTemplate.opsForHash().get(userId, "token");
            if (StringUtils.equals(token, value)) {
                chain.doFilter(request, response);
            } else {
                httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN); // 设置状态码为403
                httpResponse.setContentType("application/json"); // 设置内容类型为JSON
                httpResponse.setCharacterEncoding("UTF-8");
                httpResponse.getWriter().write("{\"error\":\"Access denied\"}"); // 返回错误信息
                return; // 终止过滤链的进一步处理
            }
        }
    }

    @Override
    public void destroy() {
        System.out.println("MyLogFilter 销毁...");
    }
}
